/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


myApp.controller('cartController',
        //['$scope'],
        function($scope, $location, cartService, $route, $cookies, postOrders, $rootScope) {
    
    $rootScope.showSearchBar = true;
    $rootScope.showWelcomeMessage = true;
    $rootScope.isLoginPage = true;
    function getOrders(){
        var orders;
        try{
            orders = JSON.parse($cookies.mealOrders);
        }
        catch(err){
            orders = [];
        }
        
        return orders;
    }
    
    
    var postMealFailure = function() {
        console.log("Failure while posting meal.");
    }
    
    cartService.getCartDetails(getOrders()).then(function(respData){
        $scope.orders = respData.data.orders;
        var orders = respData.data.orders;
        $scope.grandTotal = 0;
        $scope.totalNoOfItemsOrdered = 0;
        for(index in orders){
            var order = orders[index];
            $scope.grandTotal += order.price * order.quantity;
            $scope.totalNoOfItemsOrdered += order.quantity;
        }
    }, postMealFailure);
    
    $scope.removeItemFromCart = function(mealId){
        var orders = getOrders();
        for(index in orders){
            var order = orders[index];
            if(order.mealId == mealId){
                //id matched remove the content
                orders.splice(index, 1);
                break;
            }
        }
        $cookies.mealOrders = JSON.stringify(orders);
        $route.reload();
    }
    
    var postMealSuccess = function() {
        $rootScope.showAlert("Your order has been posted.");
        $cookies.mealOrders = JSON.stringify([]);
        $location.path('/viewMeal');
    }
    var postMealFailure = function() {
        console.log("Failure while posting meal.");
    }
    
    $scope.postOrder = function(){
        var orders;
        try{
            orders = JSON.parse($cookies.mealOrders);
        }
        catch(err){
            orders = [];
        }
        
        postOrders.postOrders(orders).then(postMealSuccess, postMealFailure);
    };
    
    
});